package net.qiqbframework.commandhandling;


import net.qiqbframework.messaging.monitoring.MonitorCallback;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * 通知消息监视器消息执行结果的回调包装器
 *
 */
public class MonitorAwareCallback<C, R> implements CommandCallback<C, R> {

    private final CommandCallback<C, R> delegate;
    private final MonitorCallback messageMonitorCallback;

    /**
     *
     */
    public MonitorAwareCallback(@Nullable CommandCallback<C, R> delegate,
                                @Nonnull MonitorCallback messageMonitorCallback) {
        this.delegate = delegate;
        this.messageMonitorCallback = messageMonitorCallback;
    }

    @Override
    public void onResult(@Nonnull CommandMessage<? extends C> commandMessage,
                         @Nonnull CommandResultMessage<? extends R> commandResultMessage) {
        if (commandResultMessage.isExceptional()) {
            messageMonitorCallback.reportFailure(commandResultMessage.exceptionResult());
        } else {
            messageMonitorCallback.reportSuccess();
        }
        if (delegate != null) {
            delegate.onResult(commandMessage, commandResultMessage);
        }
    }

}
